package com.pj.wisdomlogistics.ui.activity;

import android.Manifest;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.pj.wisdomlogistics.R;
import com.pj.wisdomlogistics.cons.Cons;
import com.pj.wisdomlogistics.mvp.contract.RepairFinishContract;
import com.pj.wisdomlogistics.mvp.frame.MvpActivity;
import com.pj.wisdomlogistics.mvp.frame.base.BaseView;
import com.pj.wisdomlogistics.mvp.presenter.RepairFinshPresenter;
import com.pj.wisdomlogistics.other.EventCenter;
import com.pj.wisdomlogistics.ui.adapter.GridImageAdapter;
import com.pj.wisdomlogistics.ui.view.GridSpacingItemDecoration;
import com.pj.wisdomlogistics.utils.ActivityManagerUtil;
import com.pj.wisdomlogistics.utils.CustomToast;
import com.pj.wisdomlogistics.utils.DensityUtil;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class RepairFinishActivity extends MvpActivity<RepairFinshPresenter> implements RepairFinishContract.View, BaseActivity.RequestPermission {

    @BindView(R.id.rv_select_pic)
    RecyclerView mRvSelectPic;
    @BindView(R.id.et_remark)
    EditText mEtRemark;
    @BindView(R.id.bt_send)
    Button mBtSend;

    private GridImageAdapter mAdapter;
    private List<LocalMedia> selectList = new ArrayList<>();
    private int maxSelectNum = 3;

    private int repairApplyId;

    @Override
    public void onError(String errorMsg) {
        dismissProgressDialog();
        CustomToast.showToast(this , errorMsg , 1000);
    }

    @Override
    public void onSuccess() {
        dismissProgressDialog();
        CustomToast.showToast(this , "提交成功" , 1000);
        EventBus.getDefault().post(new EventCenter<>(Cons.RepairInfo.REPAIR_FINISH_OK));
        ActivityManagerUtil.create().finishActivity();
    }

    @Override
    protected BaseView getBaseView() {
        return this;
    }

    @Override
    public void initView() {
        repairApplyId = getIntent().getIntExtra(Cons.RepairInfo.REPAIR_ID , -1);
        setRequestPermissionListener(this);

        if (!checkPermission(Manifest.permission.CAMERA)) {
            requestSystemPermissions(new String[]{Manifest.permission.CAMERA}, 111);
        }

        mRvSelectPic.setLayoutManager(new GridLayoutManager(this, 4, GridLayoutManager.VERTICAL, false));
        mRvSelectPic.addItemDecoration(new GridSpacingItemDecoration(4, DensityUtil.dip2px(2), false));
        mAdapter = new GridImageAdapter(this, onAddPicClickListener);
        mAdapter.setList(selectList);
        mAdapter.setSelectMax(maxSelectNum);
        mRvSelectPic.setAdapter(mAdapter);

    }

    @Override
    public void initData() {

    }

    @Override
    public int getContentView() {
        return R.layout.activity_car_finish;
    }

    @Override
    public boolean isApplyEventBus() {
        return false;
    }

    @Override
    public boolean isApplyButterKnife() {
        return true;
    }

    @Override
    public void onEventCome(EventCenter eventCenter) {

    }


    @OnClick({R.id.iv_back, R.id.bt_send})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                ActivityManagerUtil.create().finishActivity();
                break;
            case R.id.bt_send:
                if(selectList.size() == 0){
                    CustomToast.showToast(this , "请选择说明图片" , 1000);
                    return;
                }

//                if(TextUtils.isEmpty(mEtRemark.getText().toString().trim())){
//                    CustomToast.showToast(this , "请填写维修说明" , 1000);
//                    return;
//                }

                List<String> imagePath = new ArrayList<>(selectList.size());
                for (LocalMedia localMedia : selectList) {
                    imagePath.add(localMedia.getPath());
                }

                Luban.get(this)
                        .loadFiles(imagePath)
                        .putGear(Luban.THIRD_GEAR)
                        .setCompressListener(new OnCompressListener() {
                            @Override
                            public void onStart() {

                            }

                            @Override
                            public void onSuccess(File file) {

                            }

                            @Override
                            public void onSuccess(List<File> files) {
                                mPresenter.carFinish(
                                        TextUtils.isEmpty(mEtRemark.getText().toString().trim()) ? "" : mEtRemark.getText().toString().trim(),
                                        repairApplyId ,
                                        files);
                            }

                            @Override
                            public void onError(Throwable e) {
                                CustomToast.showToast(RepairFinishActivity.this ,"图片压缩失败，请重新尝试" , 1000);
                            }
                        })
                        .compress();

                showProgressDialog();
                break;
        }
    }

    @Override
    public void onRequestResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 111) {
            if (!checkPermission(Manifest.permission.CAMERA)) {
                CustomToast.showToast(RepairFinishActivity.this ,"您拒绝了拍照权限，该功能无法使用！" , 1000);
                ActivityManagerUtil.create().finishActivity();
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    mAdapter.setList(selectList);
                    mAdapter.notifyDataSetChanged();
                    break;
            }
        }
    }

    private GridImageAdapter.onAddPicClickListener onAddPicClickListener = new GridImageAdapter.onAddPicClickListener() {
        @Override
        public void onAddPicClick() {
            PictureSelector.create(RepairFinishActivity.this)
                    .openGallery(PictureMimeType.ofImage())// 全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                    .theme(R.style.picture_default_style)// 主题样式设置 具体参考 values/styles   用法：R.style.picture.white.style
                    .maxSelectNum(maxSelectNum)// 最大图片选择数量
                    .minSelectNum(1)// 最小选择数量
                    .imageSpanCount(4)// 每行显示个数
                    .selectionMode(PictureConfig.MULTIPLE)// 多选 or 单选
                    .previewImage(true)// 是否可预览图片
                    //.compressGrade(Luban.THIRD_GEAR)// luban压缩档次，默认3档 Luban.FIRST_GEAR、Luban.CUSTOM_GEAR
                    .isCamera(true)// 是否显示拍照按钮
                    .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                    .compress(false)// 是否压缩
                    //.compressMode(LUBAN_COMPRESS_MODE)//系统自带 or 鲁班压缩 PictureConfig.SYSTEM_COMPRESS_MODE or LUBAN_COMPRESS_MODE
                    //.sizeMultiplier(0.5f)// glide 加载图片大小 0~1之间 如设置 .glideOverride()无效
                    //.glideOverride(160, 160)// glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                    .selectionMedia(selectList)// 是否传入已选图片
                    .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
        }

    };
}
